package be.kuleuven.thesis.log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import java.util.TimeZone;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

public class Logger {
	private static Logger instance = new Logger();
	private FileOutputStream fOut;
	private OutputStreamWriter myOutWriter;
	private File file;
	private Context context;
	private boolean messageSend = false;
	
	private Logger() {
		file = new File(Environment.getExternalStorageDirectory()+"/sessionFile.txt");
//		try {
//			fOut = new FileOutputStream(file);
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		}
//		myOutWriter = new OutputStreamWriter(fOut);
	}
	
	public static Logger getInstance() {
		return instance;
	}
	
	public void setContext(Context context) {
		this.context = context;
	}
	
	public void makeNewFile(Context context) {
		try {
			file.delete();
			file.createNewFile();
			fOut = new FileOutputStream(file);
			myOutWriter = new OutputStreamWriter(fOut);
			messageSend = false;
			//log("Application Started");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String readFile() {
		StringBuilder contents = new StringBuilder();

		try {
			//use buffering, reading one line at a time
			//FileReader always assumes default encoding is OK!
			BufferedReader input =  new BufferedReader(new FileReader(file));
			try {
				String line = null; //not declared within while loop
				/*
				 * readLine is a bit quirky :
				 * it returns the content of a line MINUS the newline.
				 * it returns null only for the END of the stream.
				 * it returns an empty String if two newlines appear in a row.
				 */
				while (( line = input.readLine()) != null){
					contents.append(line);
					contents.append(System.getProperty("line.separator"));
				}
			}
			finally {
				input.close();
			}
		}
		catch (IOException ex){
			ex.printStackTrace();
		}

		return contents.toString();
	}
	
	private void logWithoutDate(String message) {
		try {
			myOutWriter.append(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void log(String origin, String action, Object target) {
//		if(file == null)
//			makeNewFile(context);
//		if(messageSend == true) {
//			file.delete();
//			makeNewFile(context);
//			messageSend = false;
//		}
		if(messageSend == true)
			makeNewFile(context);
		System.out.println("Log: "+action);
		try {
			String targetString = (target != null ? target.toString() : "");
			myOutWriter.append(Calendar.getInstance(TimeZone.getTimeZone("GMT+2")).getTime().toString() + "\t ; \t"+ 
								origin + "\t ; \t" + 
								action + "\t ; \t" +
								targetString +";\n");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("file was closed");
			String contents = readFile();
			makeNewFile(context);
			logWithoutDate(contents);
			log(origin, action, target);
			
		}
	}
	
	public void closeFile() {
		if(myOutWriter == null)
			return;
		try {
			myOutWriter.close();
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void sendFile(Context context) {
		if(!file.exists()) {
			System.out.println("Er bestaat nog geen file");
			Toast.makeText(context.getApplicationContext(), "There is no data to send", Toast.LENGTH_SHORT);
			return;
		}
		log("Logger","Sending File", null);
		closeFile();
		
		final Intent emailIntent = new Intent(
				android.content.Intent.ACTION_SEND);
		//
		String address = "matthiassnellings@gmail.com";
		String subject = "LogFile";
		String emailtext = "Alweer een log file";
		//
		emailIntent.setType("plain/text");

		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
				new String[] { address });

		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);

		emailIntent.putExtra(Intent.EXTRA_STREAM,
				Uri.parse("file://" + file));

		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailtext);

		context.startActivity(Intent
				.createChooser(emailIntent, "Send mail..."));
		
		messageSend = true;
	}
}
